package com.coo1.onlineorder.server;

import java.io.IOException;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;


public class TestMailSendingServlet extends HttpServlet {
    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		
		String content = req.getParameter("content");
		String sender = req.getParameter("Sender");
		String toAdd = req.getParameter("To");
		String Title = req.getParameter("Title");
		if (content == null) {
		content = "(No greeting)";
		}
		if (user != null) {
		    Properties props = new Properties();
		    Session session = Session.getDefaultInstance(props, null);
		
		    String msgBody = content;
		
		    try {
		        Message msg = new MimeMessage(session);
		        msg.setFrom(new InternetAddress(sender));
		        msg.addRecipient(Message.RecipientType.TO,
		                         new InternetAddress(toAdd));
		        msg.setSubject(Title);
		        msg.setText(msgBody);
		        Transport.send(msg);
		        resp.getWriter().println("You Mail is sent!" );
		    } catch (AddressException e) {
		        // ...
		    } catch (MessagingException e) {
		        // ...
		    }
		}
		resp.sendRedirect("/TestMailSending.jsp");
}

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
              throws IOException {
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();

        if (user != null) {
            resp.setContentType("text/plain");
            resp.getWriter().println("Hello, " + user.getNickname());
        } else {
            resp.sendRedirect(userService.createLoginURL(req.getRequestURI()));
        }

    }
	
	
}